<template>
    <div class="container">
        <div class="content-head">
            <router-link v-if="rightsButtons['add']" :to="{name: 'packetRainAdd'}">
                <el-button type="primary" size="mini">新建红包雨活动</el-button>
            </router-link>
            <el-button v-if="rightsButtons['bgEdit']" type="primary" size="mini" @click="showBaseEdit">编辑默认活动背景图片</el-button>
            <router-link v-if="rightsButtons['record']" :to="{name: 'packetRainRecord'}" style="float:right;">
              <el-button type="primary" size="mini">红包雨活动记录</el-button>
            </router-link>

        </div>
        <div class="content-middle">
            <el-form :model="form" ref="form" label-width="100px" size="mini" :inline="true">
                <el-form-item label="开始时间：" prop="startTime">
                    <el-date-picker v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期时间">
                    </el-date-picker>

                </el-form-item>
                <el-form-item label="栏目状态" prop="state">
                    <el-select v-model="form.state" placeholder="">
                        <el-option label="全部" :value="0"></el-option>
                        <el-option label="未开始" :value="1"></el-option>
                        <el-option label="抢购中" :value="2"></el-option>
                        <el-option label="已结束" :value="3"></el-option>
                    </el-select>

                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSearch()">搜索</el-button>
                    <el-button type="primary" @click="clearData()">清空搜索条件</el-button>
                </el-form-item>
            </el-form>

        </div>
        <div class="content-bottom">
            <el-table :data="list" border stripe>
                <el-table-column prop="hongbaoRainActivityId" label="活动ID"></el-table-column>
                <el-table-column prop="title" label="活动名称"></el-table-column>
                <el-table-column prop="startTime" label="开始时间"></el-table-column>
                <el-table-column label="持续时间">
                    <template slot-scope="scope">
                        <div>
                            {{scope.row.duration + 's'}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="maximumTotalAmount" label="最高总金额"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <div>
                            <span v-if="scope.row.state === 1"> 未开始</span>
                            <span v-else> {{scope.row.state === 2 ? '抢购中':'已结束'}}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="是否启用">
                    <template slot-scope="scope">
                        <div>
                            <el-switch v-model="scope.row.enabled" :disabled="true" :active-value="1" :inactive-value="0"></el-switch>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" v-if="rightsButtons['edit']">
                    <template slot-scope="scope">
                        <router-link :to="{name: 'packetRainEdit', query: {id: scope.row.hongbaoRainActivityId}}">
                          <el-button type="text">编辑</el-button>
                        </router-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @current-change="currentChange" @size-change="changeSize" :current-page="form.pageIndex" :page-size="form.pageSize" layout="sizes,total, prev, pager, next, jumper" :total="total" background>
            </el-pagination>

        </div>
        <el-dialog title="编辑红包雨活动图片（活动结束时展示用图）" :visible.sync="dialog" width="100%" @close="close()">
            <div class="dialog-body">
                <el-form :model="baseInfo" ref="baseInfo" label-width="160px" :rules="baseRule">

                  <el-form-item label="红包雨活动背景:" prop="picUrl">
                    <el-upload
                      class="avatar-uploader"
                      accept="image/*"
                      :action="upladUrl"
                      name="file"
                      :show-file-list="false"
                      :on-success="uploadSuccess"
                      :before-upload="beforeUpload">
                      <img v-if="baseInfo.picUrl" :src="baseInfo.picUrl" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>


                </el-form>

            </div>
            <span slot="footer">
                <el-button @click="close()">取 消</el-button>
                <el-button :loading="loading" type="primary" @click="comfirm()">
                  <span v-if="!loading">确 定</span>
                  <span v-else>上传中</span>
                </el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import { getPacketRainList, packetAction, getPacketsBase, savePacketsBase } from '@/api/searchMsg'
export default {
    name: 'packetRain',
    data() {
        return {
            timer: 60,
            count: 1,
            editType: 1,
            dialog: false,
            loading: false,
            baseInfo: {
              picUrl: ''
            },
            form: {
                startTime: '',
                state: 0,
                pageIndex: 1,
                pageSize: 10,
            },
            rainForm: {
                title: '',
                startTime: '',
                enabled: 0,
                hongbaoRainRuleList: [{ fromPersonNumber: 1, toPersonNumber: '', totalAmount: '' }]
            },
            orginal: {
                title: '',
                startTime: '',
                enabled: 0,
                hongbaoRainRuleList: [{ fromPersonNumber: 1, toPersonNumber: '', totalAmount: '' }]
            },
            list: [],
            total: 0,
            baseRule: {
              picUrl:[
                { required: true, message: '请选择背景图片!', trigger: 'blur' }
              ]
            },
            rule: {
                title: [
                    { required: true, message: '请输入活动名称!', trigger: 'blur' }
                ],
                startTime: [
                    { required: true, message: '请选择开始时间!', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        async getList() {
            this.form.startTime = !this.form.startTime ? '' : this.form.startTime;
            const res = await getPacketRainList(this.form);
            if (res.status === 200) {
                this.list = res.data;
                this.total = res.totalCount;
            }
        },

        initBase() {
          getPacketsBase().then(res => {
            if(!res.data){
              this.baseInfo.picUrl = ''
            } else {
              this.baseInfo = res.data
            }
          })
        },

        showBaseEdit() {
          this.dialog = true
        },
        beforeUpload() {
          this.loading = true
        },
        async uploadSuccess(res) {
          this.loading = false
          this.baseInfo.picUrl = this.replaceImgUrl(res.filePath);
        },
        close() {
          this.dialog = false;
        },
        isLastGreater() {
            let last = this.rainForm.hongbaoRainRuleList;
            if (last.length > 1) {

                if (parseInt(last[last.length - 1].totalAmount) <= parseInt(last[last.length - 2].totalAmount)) {
                    this.$message({
                        type: 'warning',
                        message: `每条规则的金额必须大于上一条规则`,
                    })
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        },
        comfirm() {
            this.$refs['baseInfo'].validate((valid) => {
                if (valid) {
                  savePacketsBase(this.baseInfo).then(res => {
                    this.$message({
                      type: 'success',
                      message: '背景图片保存成功'
                    })
                  }).catch(err => {
                    console.log(err)
                  })
                  setTimeout(this.close, 1000)
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        async save() {
            let res;
            if (this.editType === 1) {
                res = await packetAction(this.rainForm, '');
            } else {
                res = await packetAction(this.rainForm, '', 'put');
            }
            if (res.code === 200) {
                this.$message({
                    type: 'success',
                    message: res.message
                })
                this.dialog = false;
                this.close();
                this.getList();
            }
        },
        clearData() {
            this.$refs['form'].resetFields();
        },
        changeSize(size) {
            this.form.pageSize = size;
            this.getList()
        },
        onSearch() {
            this.form.pageIndex = 1;
            this.getList();
        },
        currentChange(val) {
            this.form.pageIndex = val;
            this.getList();
        },
        removeRow(index) {
            this.rainForm.hongbaoRainRuleList.splice(index, 1)
        },
        openEditWin(row) {
            this.editType = 2;
            this.dialog = true;
            this.customize();
            this.$nextTick(() => {
                this.rainForm = { ...row };
                console.log(this.rainForm)
                // this.rainForm.hongbaoRainRuleList = {...row.hongbaoRainRuleList}
            });
        },
        loopTast() {
            if (this.count < this.timer) {
                setTimeout(() => {
                    this.rainForm.title = '定时任务' + this.count;
                    this.rainForm.startTime = this.getCurrentTime();
                    this.rainForm.enabled = 1;
                    this.rainForm.hongbaoRainRuleList = [{ fromPersonNumber: 1, toPersonNumber: '3', totalAmount: '123' }]
                    this.save();
                    this.count += 1;
                    this.loopTast();
                }, 30000)

            }

        },
        getCurrentTime() {
            let myDate = new Date();
            let min = myDate.getMinutes();
            let second = myDate.getSeconds();
            if (min < 10) {
                min = '0' + min + 5;
            } else {
                min = min + 5;
            }
            if (second < 10) {
                second = '0' + second;
            }
            return '2019-07-31' + ' ' + myDate.getHours() + ":" + min + ":" + second;
        },
        customize() {
            let dailog = document.getElementsByClassName('el-dialog')[0];
            if (dailog) {
                dailog.style.maxWidth = "1000px";
            }
        },
        addRow() {
            let rainForm = this.rainForm.hongbaoRainRuleList;
            if (this.rainForm.hongbaoRainRuleList.length < 1) {
                this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: 1, toPersonNumber: '', totalAmount: '' })
            }
            if (this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber == '' || this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].totalAmount == '') {
                this.$message({
                    type: 'warning',
                    message: '请先完成上一个规则！'
                })
                return false;
            } else {
                if (this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber <= this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].fromPersonNumber) {
                    this.$message({
                        type: 'warning',
                        message: '参与人数范围结束值必须大于开始值！'
                    })
                    return false;
                } else {
                    if (rainForm.length >= 2) {
                        let parentPrice = parseInt(rainForm[rainForm.length - 2].totalAmount);
                        let childPrice = parseInt(rainForm[rainForm.length - 1].totalAmount)
                        if (childPrice > parentPrice) {
                            this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: parseInt(this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber) + 1, toPersonNumber: '', totalAmount: '' })
                        } else {
                            this.$message({
                                type: 'warning',
                                message: '总金额必须大于上一条规则！'
                            })
                        }
                    } else {
                        this.rainForm.hongbaoRainRuleList.push({ fromPersonNumber: parseInt(this.rainForm.hongbaoRainRuleList[this.rainForm.hongbaoRainRuleList.length - 1].toPersonNumber) + 1, toPersonNumber: '', totalAmount: '' })

                    }


                }
            }

        }
    },
    mounted() {
        this.getList();
        this.initBase()
        // this.loopTast();
    }
}
</script>
<style lang="scss" scoped>
.container {
  padding: 10px;
  .content-head,
  .content-middle,
  .content-bottom {
    background-color: white;
    margin: 8px 0;
    display: block;
    padding: 10px;
  }
  .el-form .el-input,
  .el-form .el-textarea,
  .el-form .el-select,
  .el-form .el-date-editor {
    width: auto !important;
  }
  .row-container {
    margin: 20px 0;
  }
}
</style>
